import SQLite from "react-native-sqlite-storage";

SQLite.DEBUG(true);
let database_name = "yyjUserInfo.db";
let db;
const User_TABLE_NAME = 'userinfo'; //用户表；

class SQLiteDB {

	//打开用户数据库；
	open() {
		db = SQLite.openDatabase({name: database_name, location: "default"}, () => {
			this._successCal("open");
		}, (error) => {
			this._errorCal("open", error);
		});
	}

	//创建用户信息数据表；
	createUserTable() {
		if(!db) {
			this.open();
		}
		db.transaction((tx) => {
			tx.executeSql(`CREATE TABLE IF NOT EXISTS ${User_TABLE_NAME} (id, name, phone, password)`);
		}, (error) => {
			this._errorCal("create Table", error.message);
		}, () => {
			this._successCal("create Table");
		})
	}

	//保存用户的注册信息；
	saveUserInfo(userId, userName, userPhone, userPwd) {
		if(db) {
			db.transaction((tx) => {
				let query = `INSERT INTO ${User_TABLE_NAME} VALUES (?,?,?,?)`;
				tx.executeSql(query, [userId, userName, userPhone, userPwd], () => {
					alert("success");
					this._successCal("insert user");
				}, (error) => {
					alert(error.message);
					this._errorCal("insert user", error.message);
				})
			}, (error) => {
				this._errorCal("transaction insert", error.message);
			}, () => {
				this._successCal("transaction insert");
			})
		}
	}

	//查询用户数据表；
	selectUserInfo(userPhone, userPwd) {
		return new Promise((resolve, reject) => {
			if (db) {
				db.transaction((tx) => {
					let query = `SELECT * FROM ${User_TABLE_NAME} WHERE phone = ? AND password = ?`
					tx.executeSql(query, [userPhone, userPwd], (tx, results) => {
						this._successCal("select user");
						let len = results.rows.length;
						if(len == 0) {
							// Toast.info("您的账号或密码有误");
							resolve("failed");
						}else{
							// for(let i = 0; i < len; i ++) {
							// 	let row = results.rows.item(i);
							// 	console.log(row);
							// }
							resolve("successed");
							// alert("登录成功")
						}
					}, (error) => {
						this._errorCal("select user", error);
					})
				}, (error) => {
					this._errorCal("transaction select", error.message);
				}, () => {
					this._successCal("transaction select");
				})
			}else{
				alert("数据库抛出异常");
			}
			
		})
	}

	//成功之后的回调;
	_successCal(name) {
		console.log("sqlite return " + name + " success");
	}

	//失败之后的回调；
	_errorCal(name, err) {
		console.log("sqlite return " + name + " error info " + err);
	}

	render() {
		return null;
	}
}

export default new SQLiteDB();